package MySQLOP;
require Exporter;
@ISA = qw(Exporter);
@EXPORT = qw(init_config);

use Data::Dumper;
use DBI;

#实例初始化
sub new
{
    my $class = shift;
    my $self = shift;
    my %parm = @_;

    bless($self,$class);
    $self->init;

    return $self;
}

#获取传递参数
sub init
{
    my $self = shift;
    my $username = $self->{'username'} or die "username must be no null!\n";
    my $passwd = $self->{'passwd'} or die "passwd must be no null!\n";
    my $dbname = $self->{'dbname'} or die "dbname must be no null!\n";
    my $host = $self->{'host'} or die "host must be no null!\n";
    my $port = 3306 if(!$self->{'port'});
	
}


#创建数据连接,将连接好的句柄返回给调用者
sub _DB_Connect
{
    my $self = shift;
    my $username = $self->{'username'};
    my $passwd = $self->{'passwd'};
    my $dbname = $self->{'dbname'};
    my $host = $self->{'host'};
    my $port = $self->{'port'};
	
    my $dsn = "DBI:mysql:database=$dbname;host=$host;port=$port";
    my $dbh = DBI->connect($dsn,$username,$passwd) or die "Can't connect to $host: $DBI::errstr";

    return $dbh;
}

#新创建的容器信息写入数据库
sub _New_Insert
{
    my $self = shift;
    my ($dbh,$container_inspect_info_ref,$container_info_ref,$business_group) = @_;

    #print Dumper($container_inspect_info_ref);
    
    #$a不用，仅仅用于接收
    my ($a,$image_native_id) = split(/:/,$container_inspect_info_ref->{'Image'});

    
    #----------获取容器信息----------
    my $ip =  $container_inspect_info_ref->{'NetworkSettings'}->{'IPAddress'};
    my $macaddress = $container_inspect_info_ref->{'NetworkSettings'}->{'MacAddress'};
    my $ipprefixlen = $container_inspect_info_ref->{'NetworkSettings'}->{'IPPrefixLen'};
    my $resolvconfpath = $container_inspect_info_ref->{'ResolvConfPath'};
    my $hostnamepath =  $container_inspect_info_ref->{'HostnamePath'};
    my $hostname = $container_inspect_info_ref->{'Config'}->{'Hostname'};
    my $status = $container_inspect_info_ref->{'State'}->{'Status'};
    my $cid = substr($container_inspect_info_ref->{'Id'},0,12); #id只保留前面12位
    my $image_id = substr($image_native_id,0,12);
    my $image_name = $container_inspect_info_ref->{'Config'}->{'Image'};
    my $portbindings = $container_inspect_info_ref->{'HostConfig'}->{'PortBindings'};

    #----去除name的第一个字符'/'
    my @name = split('/',$container_inspect_info_ref->{'Name'});
    #my $name = $nm[1];
    
    #端口映射
    my $application_port = ${$portbindings->{'8080/tcp'}}[0]->{'HostPort'};
    my $ssh_port = ${$portbindings->{'22/tcp'}}[0]->{'HostPort'};


    #print Dumper($container_info_ref);
    my $create_time =  $container_info_ref->{'Created'};
    my $create_date =  $container_info_ref->{'Labels'}->{'build-date'};

    #如果业务组不指定，默认是test
    $business_group = 'test' if(!$business_group);
    
   
    my $sql = "insert into `docker` ( `export_application_port`, `server`, `ip_address`, `status`, `network_mode`, \
                                      `image_id`, `image_name`,`cmd`, `create_time`, `create_date`, `hostname_path`, `vendor`, `name`, `restart_count`, \
                                      `links`, `cid`,  `hostname`, `is_delete`, `export_ssh_port`, `busines_group`, `macaddress`) \
                                       values (?, 'docker01.ol.line0.com',?,?, 'bridge', \
                                                ?,?, '/usr/sbin/sshd -D',?,?,?,'CentOS',?, '0', \
                                                'NULL',?,?, '0',?,?,?)";


    my $sth = $dbh->prepare($sql);   #准备
    $sth->execute($application_port,$ip,$status,$image_id,$image_name,$create_time,$create_date,$hostnamepath,$name[1],$cid,$hostname,$ssh_port,$business_group,$macaddress);
    $sth->finish;
}

sub _Group_query
{
    my $self = shift;
    my $dbh = shift;

    my @grouplist = ();
    
    my $sql = "SELECT distinct busines_group FROM docker";

    my $sth = $dbh->prepare($sql);
    $sth->execute();
    while(my @list = $sth->fetchrow_array()){
	push @grouplist,@list;
    }

    $sth->finish();
    #print Dumper(@grouplist);

    return \@grouplist;
}


#更新容器信息,status/hostname/name/restart_count
sub _Update_Container_Info
{
    
}


#获取需要映射的端口
sub _Export_Port
{
    my $self = shift;
    my $dbh = shift;

    my @port;
    my $port_ref = {};
    
    my $sql = "select port_export_next,port from value";
    my $update_sql = "update value set port_export_next = ? where name = ?";
    
    my $sth = $dbh->prepare($sql);
    $sth->execute();

    
    #my $hash_ref;
    while(my $hash_ref = $sth->fetchrow_hashref()){
	#print Dumper($hash_ref);
	$port_ref->{'tomcat_port'} = $hash_ref->{'port_export_next'} if($hash_ref->{'port'} == 8080);
	$port_ref->{'ssh_port'} = $hash_ref->{'port_export_next'} if($hash_ref->{'port'} == 22);
	$port_ref->{'dubbo_port'} = $hash_ref->{'port_export_next'} if($hash_ref->{'port'} == 20880);
    }

    #更新端口
    foreach my $key (keys %$port_ref){	
	$sth = $dbh->prepare($update_sql);
	$sth->execute($port_ref->{$key} + 1,$key);
    }
    
    $sth->finish;

    return $port_ref;
}


#--------------删除容器在数据库的信息--------------
sub _Delete_Container_Info
{
    my $self = shift;
    my ($dbh,$cid) = @_;
    
    my $sql = "delete from docker where cid = ?";

    my $sth = $dbh->prepare($sql);
    $sth->execute("$cid") or die "$@\n";
    
    $sth->finish;
}



#-------------根据group获取容器信息-----------------
sub _List_By_Group
{
    my $self = shift;
    my ($dbh,$group) = @_;
    my @list_array;

    #print $group."\n";
    my $sql = "select ip_address,name,cid,image_name,create_time,export_ssh_port,export_application_port from docker where busines_group = ?";
    #my $sql = "select name,cid,image_name,ip_address,create_time,export_ssh_port,export_application_port from docker where busines_group = ?";

    my $sth = $dbh->prepare($sql);

    $sth->execute($group);
    while(my $row_ref = $sth->fetchrow_hashref){
	push(@list_array,$row_ref);
    }

    #print Dumper(@list_array);
    return \@list_array;
    
}
